package com.whwj.heaven.auth.exception;

import com.wjwh.heaven.common.core.utils.Result;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * @author dm
 * @Date: 2021/2/25 12:11
 * @Description: 自定义认证异常返回格式
 */
@Component
public class HeavenWebResponseExceptionTranslator implements WebResponseExceptionTranslator {
    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        if (e instanceof OAuth2Exception) {
            int code = ((OAuth2Exception) e).getHttpErrorCode();
            String message = e.getMessage();
            if (message.contains("Invalid authorization code")){
                message = message.replace("Invalid authorization code", "无效的授权代码");
            }
            return ResponseEntity.status(code).body(Result.failure(code, message));
        }else if(e instanceof AuthenticationException){
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(Result.failure(HttpStatus.UNAUTHORIZED.value(),e.getMessage()));
        }
        return ResponseEntity
                .status(HttpStatus.BAD_REQUEST)
                .body(Result.failure(HttpStatus.BAD_REQUEST.value(),e.getMessage()));
    }
}
